package forks;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;

import com.riguz.forks.framework.aop.After;
import com.riguz.forks.framework.aop.Before;
import com.riguz.forks.framework.aop.CostInterceptor;
import com.riguz.forks.framework.mvc.Controller;
import com.riguz.forks.framework.mvc.Result;
import com.riguz.forks.framework.mvc.view.JsonResult;
import com.riguz.forks.framework.mvc.view.Todo;
import com.riguz.forks.framework.mvc.view.View;

import forks.model.User;
import forks.service.UserService;

public class UserController extends Controller{
    private UserService service = new UserService();
    
    @Before({CostInterceptor.class})
    public Result users(){
        System.out.println("Users");
        View view = new View("/users/index.jsp");
        view.set("msg", "Hello World!" + new Date().toString());
        
        List<User> users = this.service.list();
        view.set("users", users);
        return view;
    }
    
    public Result get(long id){
        System.out.println("Get user:" + id);
        User u = this.service.get(id);
        return new JsonResult(u);
    }
    
    @After({CostInterceptor.class})
    public Result create(){
        return new View("/users/add.jsp").set("id", this.service.nextId());
    }
    
    
    public Result save(){
        System.out.println("Saving user");
        String name = this.getParameter("user.name");
        User user = this.getParameterToBean(User.class, "user", new String[]{"name", "age", "birthday"});
        if(user == null){
            return new JsonResult("Invalid form");
        }
        System.out.println("user:" + user);
        this.service.add(user);
        return this.users();
    }
    
    public Result update(long id){
        return new Todo();
    }
    
    
    public Result lock(Long id){
        return new Todo();
    }
    
    public Result unlock(Long id){
        return new Todo();
    }
    
    public Result reset(){
        return new Todo();
    }
    
    public Result login(){
        return new Todo();
    }
    
    public Result logout(){
        return new Todo();
    }
    
    public Result delete(Long id){
        return new Todo();
    }
    
    public Result rand(Long id){
        return new Todo();
    }
    
    public Result download(String id){
        System.out.println("Download:" + id);
        return new Todo();
    }
    public static void main(String[] args){
        System.out.println("Test");
        Class<?> c = UserController.class;
        try {
            Method m = c.getMethod("get", Long.class);
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
